#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/file.h>
#include <string.h>

char r_buf[4]; /*读缓冲*/
char w_buf[4]; /*写缓冲*/
int pipe_fd[2];
pid_t pid1,pid2,pid3,pid4;

//生产者函数
int producer(int id){
    printf("producer %d is running! \n",id);
    close(pipe_fd[0]); //关闭读端
    int i = 0;
    for(i = 1;i<10;i++){
        sleep(3);//使得当前的进程让出CPU
        if(id == 1) /*生产者1*/
            strcpy(w_buf,"aaa\0");
        else /*生产者2*/
            strcpy(w_buf,"bbb\0");
        if(write(pipe_fd[1],w_buf,4) == -1)
        //当write函数返回值为-1时，说明写入数据到管道失败。这可能是因为管道已满，或者写端已经关闭。
            printf("write to pipe error\n");
    }
    close(pipe_fd[1]); //关闭写端
    printf("producer %d is over! \n",id);
    exit(id);
}

//消费者函数
int consumer(int id){
    close(pipe_fd[1]); //关闭写端
    printf("producer %d is running! \n",id);

    if(id == 1) /*消费者1*/
            strcpy(w_buf,"ccc\0");
        else /*消费者2*/
            strcpy(w_buf,"ddd\0");
    while(1){
        sleep(1);//使得当前的进程让出CPU
        strcpy(r_buf,"eee\0");//用一个差异的值把当前的读缓冲区先重置为默认状态
        if(read(pipe_fd[0],r_buf,4) == 0)//当read函数返回值为0时，说明管道中已经没有数据可读了
            break;
        printf("consumer %d get %s,while the w_buf is %s\n",id,r_buf,w_buf);
    }
    close(pipe_fd[0]); //关闭读端
    printf("consumer %d is over! \n",id);
    exit(id);
}

int main()
{
    //先进行pipe的创建
    if (pipe(pipe_fd) < 0) {
        perror("pipe create error\n");
        exit(EXIT_FAILURE);
    }

    printf("pipe is created successfully! \n");
    if((pid1 = fork()) == 0){
        printf("i am the child_1 process, my processid is %d\n", getpid());
        producer(1);
    }
    if((pid2 = fork()) == 0){
        printf("i am the child_2 process, my processid is %d\n", getpid());
        producer(2);
    }
    if((pid3 = fork()) == 0){
        printf("i am the child_3 process, my processid is %d\n", getpid());
        consumer(1);
    }
    if((pid4 = fork()) == 0){
        printf("i am the child_4 process, my processid is %d\n", getpid());
        consumer(2);
    }

    close(pipe_fd[0]); /*需要加上这两句*/
    close(pipe_fd[1]); /*否则会有生产者或者消费者永远等待*/

    //让main进程阻塞等待4个子进程都执行完毕才结束
    int i,pid,status;
    for(i = 0;i<4;i++){
        pid = wait(&status);
    }
    exit(0);
}